﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine.UI;
using UnityEngine;

// 战斗界面，植物摆放台
public class PlantPanel
{
    private Text _sunNum;
    private Transform _cardRoot;
    private RectTransform _rootRect;

    private GameObject _cardTemplate;

    // 选中将要种植的植物时，调用。plantID
    public Action<int> OnSelectPlant;

    // 当前要种植的植物图标
    private int _growingID;
    private Image _icon;
    private Transform _iconRoot;

    private Timer _moveIconTimer;

    public void Init()
    {
        var root = UIManager.instance.AddUI("UI/FightScene/PlantPanel", UILayer.Fight);
        _rootRect = root.GetComponent<RectTransform>();

        _sunNum = root.FindComponent<Text>("SunCount/Text");
        _cardRoot = root.transform.Find("Layout");

        _cardTemplate = ResMgr.instance.LoadTemplate("UI/FightScene/PlantCard") as GameObject;

        _iconRoot = root.transform.Find("Icon");
        _icon = _iconRoot.GetComponent<Image>();
        _icon.raycastTarget = false;
        _iconRoot.gameObject.SetActive(false);

        _moveIconTimer = TimerMgr.instance.CreateFrameBaseTimer(loopMoving);
    }

    // 移动图标时每帧回调
    private void loopMoving()
    {
        Vector3 worldPos;
         RectTransformUtility.ScreenPointToWorldPointInRectangle(_rootRect, Input.mousePosition, UIManager.instance.MainCamera, out worldPos);
        _iconRoot.position = worldPos;
    }

    // 展示植物卡
    public void SetCard(IEnumerable<int> plantIdList)
    {
        _cardRoot.DestoryAllChildren();

        foreach (var id in plantIdList)
        {
            var card = GameObject.Instantiate(_cardTemplate);
            card.transform.SetParent(_cardRoot, false);

            var image = card.GetComponent<Image>();
            image.sprite = GameObject.Instantiate(Resources.Load<Sprite>(PlantTable.instance[id].CardIcon));

            var btn = card.GetComponent<Button>();
            var realId = id;
            btn.onClick.AddListener(() => onClick(realId));
        }
    }

    private void onClick(int id)
    {
        // 放回植物
        if (_growingID == id)
        {
            GrowEnd();
            return;
        }

        // 显示植物
        _icon.sprite = GameObject.Instantiate(Resources.Load<Sprite>(PlantTable.instance[id].SceneIcon));
        _iconRoot.gameObject.SetActive(true);
        _growingID = id;
        _moveIconTimer.Start();

        if (OnSelectPlant != null) { OnSelectPlant(id); }
    }

    public void GrowEnd()
    {
        _growingID = -1;
        _moveIconTimer.Stop();
        _iconRoot.gameObject.SetActive(false);
    }

    private class PlantCard
    {
        public int PlantID;
        public Button Btn;
    }

}

